﻿using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Company.Core.Helper
{
    public static class JsonHelper
    {
        /// <summary>
        /// 读JSON
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="path"></param>
        /// <returns></returns>
        public static T Load<T>(string path)
        {
            if (!File.Exists(path))
            {
                return default(T);
            }
            string content = File.ReadAllText(path);
            return JsonConvert.DeserializeObject<T>(content);
        }

        /// <summary>
        /// 将对象写成JSON文件
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="fullName"></param>
        /// <param name="indented"></param>
        public static string Write(object obj, string fullName, bool indented = false)
        {
            Formatting f = indented ? Formatting.Indented :Formatting.None;
            var content = JsonConvert.SerializeObject(obj, f);
            File.WriteAllText(fullName, content);
            return content;
        }
        
        /// <summary>
        /// 深拷贝
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static T DeepClone<T>(this T obj) where T: class
        {
            string json = Serializer(obj);
            return Deserializer<T>(json);
        }

        public static string Serializer(object obj, bool indented = false) 
        {
            Formatting f = indented ? Formatting.Indented : Formatting.None;
            return JsonConvert.SerializeObject(obj, f);
        }

        public static T Deserializer<T>(string json)
        {
            return JsonConvert.DeserializeObject<T>(json);
        }

        public static DataTable toDataTable<T>(List<T> list) where T : class
        {
            string json = JsonConvert.SerializeObject(list);
            return JsonConvert.DeserializeObject<DataTable>(json, new DataTableConverter());
        }
    }
}
